export function parseAttrs(attrs: string) {
  try {
    return JSON.parse(attrs)
  }
  catch (error) {
    console.error('Attrs转换失败:', error)
    return {}
  }
}

export function parseEvent(events: any[]) {
  if (!events) {
    return {}
  }
  const res = {}
  events.forEach((item) => {
    (res as Record<string, any>)[item.name] = parseFunction(item.code)
  })
  return res
}

// 转换为实际函数
export function parseFunction(funcStr: string) {
  if (!funcStr) {
    return null
  }
  try {
    // eslint-disable-next-line no-new-func
    return new Function(`return ${funcStr}`)()
  }
  catch (error) {
    console.error('函数转换失败:', error)
    return null
  }
}
// 生成表单规则
export function generateFormRules(formItemRules: any) {
  if (!formItemRules) {
    return []
  }
  return formItemRules.map((item: any) => {
    return {
      required: item.required,
      message: item.message,
      trigger: item.trigger || ['blur', 'change'],
      validator: item.validateCondition
        ? async (rule: any, value: any, callback: any) => {
          if (await item.validateCondition(value)) {
            callback()
          }
          else {
            callback(new Error(item.message))
          }
        }
        : undefined,

    }
  })
}
